package com.redlight.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by chao on 2019/1/23.
 */
public abstract class AbstractCallablePoolTask<E,T> implements IPoolCallableTask<E,T> {
    private Logger logger= LoggerFactory.getLogger(getClass());
    protected String threadId="";//线程id
    protected  long startTim=0;//开始时间
    protected Thread t=null;
    protected  ThreadPool pool=null;
    protected T param=null;
    protected boolean runFlg=true;

    /**
     *
     * @param id
     * @param pool
     * @param param
     */
    @Override
    public void init(String id, ThreadPool pool, T param) {
        this.param=param;
        this.threadId=id;
        this.pool=pool;
    }

    @Override
    public String getThreadId() {
        return threadId;
    }
    public void setThreadId(String threadId){
        this.threadId=threadId;
    }

    @Override
    public long getStartTim() {
        return startTim;
    }

    public void  setStartTim(long startTim){
        this.startTim=startTim;
    }


//    @Override
    public void stop()  {
        if(t.isAlive()){
            t.interrupt();
        }
    }

//    @Override
    public Thread getT() {
        return t;
    }
    public void setT(Thread t){
        this.t=t;
    }

//    @Override
//    public boolean getRunnFlg() {
//        return false;
//    }

    @Override
    public E call() throws Exception {
        startTim=System.currentTimeMillis();
        E result=null;
        t=Thread.currentThread();
        try {
            result=excuteTask(param);
            runFlg=false;
            return result;
        }catch (Exception e){
            logger.info(threadId+"线程池运行中出现异常",e);
            throw new Exception(e);
        }

    }

    public abstract E excuteTask(T param)throws  Exception;

    public ThreadPool getPool(){
        return pool;
    }

    public void setPool(ThreadPool pool){
        this.pool=pool;
    }
    public  T getParam(){
        return param;
    }

    public void set(T param){
        this.param=param;
    }

    public boolean isRunFlg(){
        return runFlg;
    }
    public void setRunFlg(boolean runFlg){
        this.runFlg=runFlg;
    }

}
